package com.alibaba.nacos.naming.utils;

import com.alibaba.nacos.naming.core.v2.client.Client;
import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo;
import org.apache.commons.collections4.MapUtils;

import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

public class DistroUtils {
    public static int hash(Client client) {
        //        if (!(client instanceof IpPortBasedClient)) {
        //            return 0;
        //        }

        Set<Integer> aDefault = client.getAllPublishedService().stream().map(service -> {
            InstancePublishInfo instancePublishInfo = client.getInstancePublishInfo(service);
            double weight = MapUtils.getDouble(instancePublishInfo.getExtendDatum(), "publishInstanceWeight", 1.0D);
            Boolean enabled = MapUtils.getBoolean(instancePublishInfo.getExtendDatum(), "publishInstanceEnable", true);
            String cluster = Optional.ofNullable(instancePublishInfo.getCluster()).orElse("DEFAULT");
            return Objects.hash(service.getNamespace(), service.getGroup(), service.getName(), service.isEphemeral(), instancePublishInfo.getIp(), instancePublishInfo.getPort(), weight,
                                instancePublishInfo.isHealthy(), enabled, cluster, instancePublishInfo.getExtendDatum());
        }).collect(Collectors.toSet());
        return Objects.hash(client.getClientId(), aDefault);
    }
}
